package com.hst.web.base.proxy;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.hst.core.Page;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.dao.ORQuery;
import com.hst.core.dao.ORQuery.Op;
import com.hst.core.json.JsonUtil;
import com.hst.core.meta.MetaData;
import com.hst.core.meta.MetaRepository;
import com.hst.core.meta.proxies.DefaultDataProxy;
import com.hst.web.base.entity.TVehicleSub;
import com.hst.web.base.service.UserRoleService;
import com.hst.web.base.ui.CompanyVehicleReview;
import com.hst.web.base.ui.VehicleSub;
import com.hst.web.common.utils.ImageUtils;

public class CompanyVehicleReviewProxy extends DefaultDataProxy {

	@Autowired
	IORDao dao;

	@Autowired
	ISQLDao sql;

	@Autowired
	MetaRepository mr;

	@Override
	@SuppressWarnings({ "unchecked" })
	public Page<?> list(Map<String, ?> query, int pageIdx) {
		UserRoleService.addCompanyEmpParam((Map<String, Object>) query);
		return sql.list("vehicle.list-company-vehicle", query, pageIdx, Page.getPageSize());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<?> list(Map<String, ?> query) {
		UserRoleService.addCompanyEmpParam((Map<String, Object>) query);
		return sql.query("vehicle.list-company-vehicle", query);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object save(MetaData data) throws Exception {
		CompanyVehicleReview meta = (CompanyVehicleReview) data;

		if (StringUtils.isEmpty(meta.getVehicleCode()))
			meta.setVehicleCode(((CompanyVehicleReview) super.save(data)).getVehicleCode());
		else
			super.save(data);
		for (TVehicleSub d : dao.list(TVehicleSub.class, new ORQuery(Op.eq, "vehicleCode", meta.getVehicleCode()))) {
			dao.delete(d);
		}
		if (meta.getVehicleSub() != null)
			for (VehicleSub sub : meta.getVehicleSub()) {
				if (!StringUtils.isEmpty(sub.getAttrValue())) {
					sub.setVehicleCode(meta.getVehicleCode());
					dao.save(mr.getMetaConvert("vehicle-sub").toEntity(sub));
				}
			}

		// 图片旋转处理
		if (!StringUtils.isEmpty(meta.getDeg())) {
			ImageUtils.imgsRotate((Map<String, Integer>) JsonUtil.read(meta.getDeg(), Map.class), meta);
		}

		// 图片反转处理
		if (!StringUtils.isEmpty(meta.getReverse())) {
			ImageUtils.imgsReverse((Map<String, Integer>) JsonUtil.read(meta.getReverse(), Map.class), meta);
		}

		return meta;
	}

}
